package demo2;

//二叉搜索树
public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root = null;
    /**
     * 查找二叉搜索树中指定的val值
     */
    public TreeNode find(int val) {
        TreeNode cur = root;
        while(cur != null) {
            if (cur.val == val) {
                return cur;
            }
            if(cur.val < val) {
                cur = cur.right;
            } else {
                cur = cur.left;
            }
        }
        return cur;
    }

    /**
     * 插入一个数据
     */
    public void insert(int val) {
        TreeNode Node = new TreeNode(val);
        if (root == null) {
            root = Node;
            return;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null) {
            if (cur.val < val) {
                parent = cur;
                cur = cur.right;
            } else if (cur.val > val){
                parent = cur;
                cur = cur.left;
            }
        }
        if (parent.val < val) {
            parent.right = Node;
        } else {
            parent.left = Node;
        }
    }





}
